from concurrent.futures import ThreadPoolExecutor
from model import ShopType
from utils.redis import Redis
import time
from app import app

pool = ThreadPoolExecutor(max_workers=300)
nums = 0
shoptypes = None


# 测试python单个线程访问redis能达到1万的访问量，多线程最多可以达到10万的访问量
def queryShopType():
    global nums, shoptypes
    with app.app_context():
        for i in range(5):
            shoptypes = ShopType.query.first()
            Redis.incrby("ince:test", 1)
            nums += 1


# 单线程QPS大概在1200左右
start = time.time()
for _ in range(1000):
    queryShopType()
print(time.time() - start)  # 3.794006586074829
print(nums)  # 5000

# 发现多线程速度也一样，说明python请求数据库多线程几乎不能起作用，mysql还是太慢了，不足以用多线程
start = time.time()
value = int(Redis.get("ince:test"))
for _ in range(1000):
    pool.submit(queryShopType)
while True:
    new_value = int(Redis.get("ince:test"))
    if new_value == value + 1000 * 5:
        break
    time.sleep(0.1)  # 因为GIL锁，必须加耗时请求或者sleep或者print
# 或者这样统计也可以
# while nums != 1000 * 5:
#     time.sleep(0.1)  # 必须sleep不然使用死循环会因为GIL锁的存在导致占用全部的资源，其他线程无法执行，当然print也有一点用，最好用sleep
#     pass
print(time.time() - start) # 3.7366185188293457

pool.shutdown()
